from Lexicon import Lexicon
from ML import ML
from config import *
from TranslationModel import TranslationModel

class OfflineTranslationModel:
	'''
	compute offline sum P(q|w)*P(w|D)
	'''
	def create(self):
		lexicon = Lexicon()
		lexicon.load()
		doc_list = []
		offline_tm = []
		for doc in xrange(doccount):
			ml = ML(str(doc))
			ml.load()
			doc_list.append(ml)
		trans_model = TranslationModel()
		trans_model.load()
		for doc in xrange(doccount):
			print 'Processing doc ' + str(doc)
			dic = {}
			for wordid in doc_list[doc].getWordsList():
				extensionlist = trans_model.getExtensionList(wordid)
				for trans_id in extensionlist:
					if dic.has_key(trans_id):
						dic[trans_id] = dic[trans_id] + trans_model.getProb(wordid, trans_id) *	doc_list[doc].getProb(wordid)
					else:
						dic[trans_id] = trans_model.getProb(wordid, trans_id) *	doc_list[doc].getProb(wordid)
			offline_tm.append(dic)
		f = open(Offline_TM_path, 'w')
		for doc in xrange(doccount):
			line = ''
			for (key, value) in offline_tm[doc].items():
				line = line + str(key) + ':' + str(value) + ' '
			line = line + '\n'
			f.write(line)
	def load(self):
		self.offline_tm = []
		f = open(offline_TM_path, 'r')
		lines = f.readlines()
		f.close()
		for i in xrange(len(lines)):
			items = lines[i].split()
			dic = {}
			for item in items:
				dic[int(item.split(':')[0])] = float(item.split(':')[1].strip())
			self.offline_tm.append(dic)
	
	def getProb(self, docId, wordId):
		if self.offline_tm[docId].has_key(wordId):
			return self.offline_tm[docId][wordId]
		else:
			return 0.0

if __name__ == '__main__':
	otm = OfflineTranslationModel()
	otm.create()
	otm.load()
	print otm.getProb(5182, 10242)
